import { Button, Card, Input, Form, InputNumber, Select,Checkbox,Alert,Tooltip,Upload,Table,Radio,Rate} from 'antd';
import { connect,history} from 'umi';
import { InfoCircleOutlined,LoadingOutlined,PlusOutlined,MinusCircleOutlined} from '@ant-design/icons';
import React, { useEffect,useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import db from '@/utils/localstorage';
import { upload } from './service';
import SupCard from './supCard';
import {HasPermission} from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);

const FormItem = Form.Item;
const { TextArea } = Input;
let index=0
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const BasicForm = props => {
  const { submitting,dispatch,coachList,match,lesson,cardList,shopList} = props;
  const [showPublicUsers, setShowPublicUsers] = React.useState(false);
  const [imageUrl, setImageUrl] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [classHourType, setClassHourType] = React.useState('1');
  const [tabActiveKey, setTabActiveKey] = React.useState('lessonInfo');
  const [courseType, setCourseType] = React.useState("");
  const actionRef = useRef();
  const columns = [
    {
      title: '课程',
      dataIndex: 'courseName',
    },
    {
      title: '时长',
      dataIndex: 'courseDuration',
      hideInSearch:true
    },
    {
      title: '排序',
      dataIndex: 'sorting',
      hideInSearch:true
    },
    {
      title: '可预约人数',
      dataIndex: 'maximumAttendance',
      hideInSearch:true
    },
  ];
  useEffect(() => {
    if (dispatch) {
       dispatch({
        type: 'cubeLesson/fetchLesson',
        payload:{
          id:match.params.id
        }
      }).then((result)=>{
        if(result.coursePicture){
          setImageUrl(result.coursePicture)
        }
        form.resetFields()
      })
      dispatch({
        type: 'cubeLesson/fetchCoach',
        payload: {
          empType:2,
        },
      })
      dispatch({
        type: 'cubeLesson/fetchShopList',
        payload:{
          userId:db.get("user").userId
        }
      })
      dispatch({
        type: 'cubeLesson/queryMemberCardInfoByCourseId',
        payload: {
          courseId:match.params.id,
        },
      })
     }
     setCourseType(props.match.params.courseType)
     if(props.location.query){
      let from=props.location.query.from
      if(from=='card'){
        setTabActiveKey('supportCard')
      }
     }
   }, []);

  const [form] = Form.useForm();
  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 20, offset: 7 },
    },
  };
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 7,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 14,
      },
      md: {
        span: 14,
      },
    },
  };
  const submitFormLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 10,
        offset: 7,
      },
    },
  };


  const onFinish = async() => {
    const values = await form.validateFields();
    const { dispatch } = props;
    if(imageUrl){
      values.coursePicture=imageUrl
    }
    if(Array.isArray(values.lableList)){
      let lableList = values.lableList
      values.lableList=[]
      lableList.map((item)=>{
        values.lableList.push({
          labelName:item
        })
      })
    }
    if(values.isStartUpClass){
      values.isStartUpClass="1"
    }else{
      values.isStartUpClass="2"
    }
    if(lesson){
      values.id=lesson.id;
    }
    if(courseType=='3'){
      values.type = courseType
    }
    dispatch({
      type: 'cubeLesson/update',
      payload: values,
    }).then((res)=>{
      if(res){
        if(courseType=='1'){
          history.push(`/lesson/schedule?tabActiveKey=lesson`)
        }else if(courseType=='3'){
          history.push(`/lesson/private?tabActiveKey=lesson`)
        }
      }
    })
  };


  const uploadButton = <><div>{loading?<LoadingOutlined />:<PlusOutlined />}<div className="ant-upload-text">上传</div></div></>
  
  //课时费类型选择
  const classHourTypeChange = e =>{
    setClassHourType(e.target.value)
  }

  const onTabChange = tabActiveKey =>{
    setTabActiveKey(tabActiveKey)
  }

  const customRequest = (detail) => {
    setLoading(true)
    const formData = new FormData();
    formData.append('file',detail.file);
    upload(formData).then((result)=>{
      setLoading(false)
      if(result.code==0){
        setImageUrl(result.data)
      }
    })
}

const go2AddLesson = ()=>{
  setTabActiveKey("lessonInfo")
}

  const submitAndSupCard =async () =>{
    const values = await form.validateFields();
    const { dispatch } = props;
    if(imageUrl){
      values.coursePicture=imageUrl
    }
    if(Array.isArray(values.lableList)){
      let lableList = values.lableList
      values.lableList=[]
      lableList.map((item)=>{
        values.lableList.push({
          labelName:item
        })
      })
    }
    if(values.isStartUpClass){
      values.isStartUpClass="1"
    }else{
      values.isStartUpClass="2"
    }
    if(lesson){
      values.id=lesson.id;
    }
    dispatch({
      type: 'cubeLesson/update',
      payload: values,
    }).then((res)=>{
      setTabActiveKey("supportCard")
    })
  }
  return (
    <PageHeaderWrapper
      tabActiveKey={tabActiveKey}
      onTabChange={onTabChange}
      tabList={[
        {
          key: 'lessonInfo',
          tab: '课程信息',
        },
        {
          key: 'supportCard',
          tab: '支持会员卡',
        } 
      ]}
    >
     {
       tabActiveKey=='lessonInfo'&&<>
         <Alert message="排期时课时所支持的会员卡、课时费类型、最少开课人数，将同步课程相关设置，排期后此类设置项将不随课程设置项的修改而变动" type="info" showIcon />
            <Form
                style={{
                  marginTop: 8,
                }}
                form={form}
                name="basic"
                initialValues={lesson}
              >
            <Card style={{marginBottom: 24}} bordered={false}>
                <FormItem
                  {...formItemLayout}
                  label="课程名称"
                  name="courseName"
                  rules={[
                    {
                      required: true,
                      message: '请输入课程名称',
                    },
                  ]}
                >
                  <Input placeholder="请输入"/>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="课程图片"
                  name="coursePicture"
                >
                 <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  customRequest={customRequest}
                >
                  {imageUrl ? <img src={`http://mmm.supercube.vip/${imageUrl}`} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>
                &nbsp;&nbsp;<span style={{fontSize:12}}>建议正方形图片，大小不超过2M。支持格式jpg、jpeg、gif、png</span>
                </FormItem>
                {/* <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                    添加视频地址&nbsp;
                    <em>
                      <Tooltip title="视频地址添加成功后，会在会员端-课程详情页顶部展示该视频">
                        <InfoCircleOutlined
                          style={{
                            marginRight: 4,
                          }}
                        />
                      </Tooltip>
                    </em>
                  </span>
                  }
                  name="videoAddress"
                >
                  <Input placeholder="请输入"/>
                </FormItem> */}
                <FormItem
                  {...formItemLayout}
                  label="课程时长"
                  name="courseDuration"
                  rules={[
                    {
                      required: true,
                      message: '请输入课程时长',
                    },
                  ]}
                >
                  <InputNumber
                    min={0}
                    style={{width:'100%'}}
                    formatter={value => `${value}分钟`}
                    parser={value => value.replace('分钟', '')}
                  />
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                    最多上课人数&nbsp;
                    <em>
                      <Tooltip title={
                        <>
                          指您这节课最多允许多少个会员预约并上课。<br/>
                          该数字只影响会员自主预约，当达到人数上限时会员不可再预约（如果启动候补预约功能，则会员此时进入候补）。<br/>
                          此数字不影响管理员、教练代预约。即当预约人数已满时，管理员或者教练仍可以替会员做代预约，即最终上课人数超过您设置的最多上课人数。请根据实际情况使用该代预约功能。<br/>
                        </>
                      }>
                        <InfoCircleOutlined
                          style={{
                            marginRight: 4,
                          }}
                        />
                      </Tooltip>
                    </em>
                  </span>
                  }
                  name="maximumAttendance"
                  rules={[
                    {
                      required: true,
                      message: '请输入最多上课人数',
                    },
                  ]}
                >
                  <InputNumber
                    min={0}
                    style={{width:'100%'}}
                    formatter={value => `${value}人`}
                    parser={value => value.replace('人', '')}
                  />
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="课程类目"
                  name="category"
                >
                    <Radio.Group>
                        {
                            courseType=='3'&&db.get("dictTypeList")&&db.get("dictTypeList")["private_course_catalogue"].map((item,index)=><Radio value={item.value} key={index}>{item.label}</Radio>)
                        }
                        {
                            courseType=='1'&&db.get("dictTypeList")&&db.get("dictTypeList")["group_course_catalogue"].map((item,index)=><Radio value={item.value} key={index}>{item.label}</Radio>)
                        }
                  </Radio.Group>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="教练"
                  name="coachId"
                >
                  <Select style={{ width: '100%' }} placeholder="请选择">
                    {
                      coachList&&coachList.map((item,index)=><Select.Option key={index} value={item.userId}>{item.name}</Select.Option>)
                    }
                  </Select>
                </FormItem>
                {
                  courseType=='1'&& <FormItem
                  {...formItemLayout}
                  label="课程类型"
                  name="type"
                  rules={[
                    {
                      required: true,
                      message: '请选择课程类型',
                    },
                  ]}
                >
                   <Radio.Group>
                    {
                            db.get("dictTypeList")&&db.get("dictTypeList")["course_type"].map((item,index)=>{
                             if((courseType=='1')&&(item.value=='1'||item.value=='2'||item.value=='4')){
                                return <Radio value={item.value} key={index}>{item.label}</Radio>
                              }
                            })
                        }
                  </Radio.Group>
                </FormItem>
                }
                {
                  courseType=='3'&& <FormItem
                  {...formItemLayout}
                  label="次卡扣卡系数"
                  name="onceCardCoefficient"
                  rules={[
                    {
                      required: true,
                      message: '请填写次卡扣卡系数',
                    },
                  ]}
                >
                   <InputNumber
                    min={0}
                    style={{width:'100%'}}
                  />
                </FormItem>
                }
                <FormItem
                  {...formItemLayout}
                  label="课程难易度"
                  name="difficulty"
                >
                  <Rate/>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="课时费类型"
                  name="classHourType"
                >
                    <Radio.Group onChange={classHourTypeChange}>
                        {
                            db.get("dictTypeList")&&db.get("dictTypeList")["class_hour_fee_type"].map((item,index)=><Radio value={item.value} key={index}>{item.label}</Radio>)
                        }
                  </Radio.Group>
                </FormItem>
                {
                  classHourType=="1"&&<FormItem
                  {...formItemLayout}
                  label="课时费"
                  name="classHour"
                  >
                  <InputNumber
                    min={0}
                    style={{width:'100%'}}
                    formatter={value => `${value}元/节`}
                    parser={value => value.replace('元/节', '')}
                  />
                  </FormItem>
                }
                 {
                  classHourType=="2"&&<FormItem
                  {...formItemLayout}
                  label="课时费"
                  name="classHour"
                  >
                  <InputNumber
                  min={0}
                  style={{width:'100%'}}
                  formatter={value => `${value}元/人`}
                  parser={value => value.replace('元/人', '')}
                />
                  </FormItem>
                }
                <FormItem
                  {...formItemLayout}
                  label="销售价格"
                  name="sellPrice"
                  rules={[
                    {
                      required: true,
                      message: '请输入销售价格',
                    },
                  ]}
                >
               <InputNumber
                  min={0}
                  style={{width:'100%'}}
                  formatter={value => `${value}元/节`}
                  parser={value => value.replace('元/节', '')}
                />
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                    人数不足不开课&nbsp;
                    <em>
                      <Tooltip title="如果勾选了此项，则表示在规定时间内，如果成功预约的会员数没有达到您设置的最少开课人数，则该课程自动取消。">
                        <InfoCircleOutlined
                          style={{
                            marginRight: 4,
                          }}
                        />
                      </Tooltip>
                    </em>
                  </span>
                  }
                  valuePropName="checked"
                  name="isStartUpClass"
                >
                <Checkbox>是</Checkbox>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="最少开课人数"
                  name="minimumNumberClasses"
                >
                  <InputNumber
                    min={0}
                    style={{width:'100%'}}
                    formatter={value => `${value}人`}
                    parser={value => value.replace('人', '')}
                  />
                </FormItem>
                {/* <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                    课程备注&nbsp;
                    <em>
                      <Tooltip title="用户预约课程时，在预约按钮上方会显示课程备注">
                        <InfoCircleOutlined
                          style={{
                            marginRight: 4,
                          }}
                        />
                      </Tooltip>
                    </em>
                  </span>
                  }
                  name="bz"
                >
                  <TextArea rows={4} placeholder="请输入"/>
                </FormItem> */}
                <Form.List name="lableList">
                  {(fields, { add, remove }) => {
                    return (
                      <div>
                        {fields.map((field, index) => (
                          <Form.Item
                            {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                            label={index === 0 ? '课程标签' : ''}
                            rules={[
                              {
                                required: true,
                                message: '请输入课程标签',
                              },
                            ]}
                            key={field.key}
                          >
                            <Form.Item
                              {...field}
                              validateTrigger={['onChange', 'onBlur']}
                              noStyle
                            >
                              <Input placeholder="单个标签限10个字" style={{ width: '300px' }} />
                            </Form.Item>
                            {fields.length > 1 ? (
                              <MinusCircleOutlined
                                className="dynamic-delete-button"
                                style={{ margin: '0 8px' }}
                                onClick={() => {
                                  remove(field.name);
                                }}
                              />
                            ) : null}
                          </Form.Item>
                        ))}
                        <Form.Item {...formItemLayoutWithOutLabel}>
                          <Button
                            type="dashed"
                            onClick={() => {
                              ++index
                              console.log('fields',fields,index)
                              add();
                            }}
                            style={{ width: '300px' }}
                          >
                            <PlusOutlined /> 添加
                          </Button>
                        </Form.Item>
                      </div>
                    );
                  }}
                </Form.List>
                <FormItem
                  {...formItemLayout}
                  label="课程介绍"
                  name="courseIntroduction"
                >
                  <TextArea rows={4} placeholder="请输入"/>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="排序"
                  name="sorting"
                >
                  <InputNumber
                    min={0}
                    placeholder="请选择"
                    style={{width:'100%'}}
                  />
                </FormItem>
                {/* <FormItem
                  {...formItemLayout}
                  label="课表显示背景色"
                  name="bgColor"
                >
                  <Select style={{ width: '100%' }} placeholder="请选择">
                    <Select.Option value="1"><div className={styles.option} style={{background:"white"}}></div><div className={styles.row}>白色</div></Select.Option>
                    <Select.Option value="2"><div className={styles.option} style={{background:"green"}}></div><div className={styles.row}>绿色</div></Select.Option>
                    <Select.Option value="3"><div className={styles.option} style={{background:"#99CCFF"}}></div><div className={styles.row}>浅蓝色</div></Select.Option>
                    <Select.Option value="4"><div className={styles.option} style={{background:"yellow"}}></div><div className={styles.row}>黄色</div></Select.Option>
                    <Select.Option value="5"><div className={styles.option} style={{background:"red"}}></div><div className={styles.row}>红色</div></Select.Option>
                    <Select.Option value="6"><div className={styles.option} style={{background:"purple"}}></div><div className={styles.row}>紫色</div></Select.Option>
                    <Select.Option value="7"><div className={styles.option} style={{background:"#99FFFF"}}></div><div className={styles.row}>粉蓝色</div></Select.Option>
                  </Select>
                </FormItem> */}
                <FormItem
                  {...submitFormLayout}
                  style={{
                    marginTop: 32,
                  }}
                >
                  <Button type="primary" onClick={onFinish} loading={submitting}>
                  提交
                  </Button>
                  <Button
                    style={{
                      marginLeft: 8,
                    }}
                    type="primary"
                    onClick={submitAndSupCard}
                  >
                    保存并设置课程支持会员卡
                  </Button>
                  <Button
                    style={{
                      marginLeft: 8,
                    }}
                    onClick={()=>window.history.back()}
                  >
                    返回
                  </Button>
                </FormItem>
            </Card>
            </Form>
       </>
     }
     {
       tabActiveKey=='supportCard'&&<>
        <Alert message="课程相关设置项（支持会员卡、课时费类型、最小开课人数）仅作为课程排期时的模板使用，排期后再进行修改不会影响已排过的课时。" type="info" showIcon />
        {
          match.params.id&&<SupCard courseId={match.params.id}/>
        }
        {
          !match.params.id&&<Alert style={{marginTop:32}} message={<>您还没有添加团课课程，请先添加 <a onClick={go2AddLesson}>团课课程</a></>} type="warning" showIcon />
        }
       </>
     }
    </PageHeaderWrapper>
  );
};

export default connect(({ loading,cubeLesson }) => ({
  lesson: cubeLesson.lesson,
  cardList: cubeLesson.cardList,
  coachList: cubeLesson.coachList,
  submitting: loading.effects['cubeLesson/add'],
  shopList:cubeLesson.shopList,
}))(BasicForm);
